package com.yanwq.nwa;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yanwq.nwa.im.ChatMgr;
import com.yanwq.nwa.im.EventCallback;
import com.yanwq.nwa.im.EventMgr;
import com.yanwq.nwa.entity.Message;
import com.yanwq.nwa.event.MessageEvent;
import com.yanwq.nwa.message.MailBoxActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.greendao.query.WhereCondition;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    @BindView(R.id.main_refresh)
    SwipeRefreshLayout mainRefresh;
    @BindView(R.id.main_rv)
    RecyclerView mainRv;
    @BindView(R.id.activity_main)
    LinearLayout activityMain;

    MainAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        registerChat();

        RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
        mainRv.setLayoutManager(manager);
        mainRv.setAdapter(adapter = new MainAdapter());
        mainRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshRV();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unregisterChat();
    }

    private void registerChat() {
        EventMgr.getInstance().registerEventCallback(registerCallback);
        ChatMgr.register();
    }

    private void unregisterChat() {
        EventMgr.getInstance().unregisterEventCallback(registerCallback);
    }

    private EventCallback registerCallback = new EventCallback() {
        @Override
        public void onSuccess(final String message) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    JSONObject jsonObject = JSON.parseObject(message);
                    if ("register".equalsIgnoreCase(jsonObject.getString("event"))) {
                        Toast.makeText(getApplicationContext(), R.string.register_chat_success, Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

        @Override
        public void onFailure(Failure failure) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), R.string.chat_server_disconnected, Toast.LENGTH_SHORT).show();
                }
            });
            mainRefresh.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ChatMgr.register();
                }
            }, 10 * 1000);
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.main_mail_box:
                startActivity(new Intent(this, MailBoxActivity.class));
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Subscribe
    public void onEvent(MessageEvent event) {
        refreshRV();
    }

    private List<Message> getMessageList() {
        return MApplication.getDaoSession().getMessageDao().queryBuilder().where(new WhereCondition.StringCondition("toUuid != 'all'")).distinct().list();
    }

    private void refreshRV() {
        adapter.refresh(getMessageList());
        mainRefresh.setRefreshing(false);
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
}
